package com.mano233.server.controller;

import com.mano233.server.config.json.annotation.JsonCustomFilter;
import com.mano233.server.config.security.UserCustomDetails;
import com.mano233.server.po.*;
import com.mano233.server.po.ResponseStatus;
import com.mano233.server.service.serviceImpl.EventsServiceImpl;
import com.mano233.server.service.serviceImpl.FastDfsServiceImpl;
import com.mano233.server.service.serviceImpl.FormServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;

/**
 * @author mano233
 */
@CrossOrigin(maxAge = 3600)
@Api("事件相关接口")
@RestController
@Validated
public class EventController {
    private final EventsServiceImpl eventsServiceImpl;
    private final FormServiceImpl formService;
    private static Logger logger = LoggerFactory.getLogger(FastDfsServiceImpl.class);

    public EventController(EventsServiceImpl eventsServiceImpl, FormServiceImpl formService) {
        this.eventsServiceImpl = eventsServiceImpl;
        this.formService = formService;
    }

    @ApiOperation(value = "新建事件")
    @PostMapping("/event")
    public ResponseMessage addEvent(Authentication authentication) {
        UserCustomDetails details = (UserCustomDetails) authentication.getPrincipal();
        int newEventId = eventsServiceImpl.addEvent(details.getUserId());
        return new ResponseMessage(ResponseStatus.INFO, newEventId, "新建了一份新的表单！");
    }

    @ApiOperation(value = "更新事件")
    @PutMapping("/event")
    public ResponseMessage update(@RequestBody Events updateEvent, Authentication authentication) {
        UserCustomDetails details = (UserCustomDetails) authentication.getPrincipal();
        Events oldEvent = eventsServiceImpl.getEventById(updateEvent.getEventId());
        if (!oldEvent.getEventAdmin().equals(details.getUserId())) {
            return new ResponseMessage(ResponseStatus.ERROR, "无权更新！");
        }
        return new ResponseMessage(ResponseStatus.INFO, eventsServiceImpl.updateEvent(updateEvent, oldEvent), "更新成功！");
    }

    @ApiOperation(value = "获取事件详情")
    @GetMapping("/event/{id}")
    public ResponseMessage getEvents(@PathVariable int id) {
        Events events = eventsServiceImpl.getEventById(id);
        if (events == null) {
            return new ResponseMessage(ResponseStatus.WARN, "事件不存在，或已被删除");
        }
        return new ResponseMessage(ResponseStatus.SUCCESS, events);
    }

    @GetMapping("/event/{eventId}/form")
    @ApiOperation(value = "获取事件下的表单")
    @JsonCustomFilter(type = User.class, filter = {"userPwd"})
    public ResponseMessage getEventForm(String type, @PathVariable int eventId) {
        switch (type) {
            case "audit":
                return new ResponseMessage(ResponseStatus.SUCCESS, formService.getAuditForm(eventId));
            case "access":
                return new ResponseMessage(ResponseStatus.SUCCESS, formService.getAccessForm(eventId));
            default:
                return null;
        }
    }

    @GetMapping("/event/admin")
    @ApiOperation(value = "获取管理员所管理的事件")
    @JsonCustomFilter(type = Events.class, filter = {"eventContent"})
    public ResponseMessage getAdminEvents(Authentication authentication) {
        UserCustomDetails userDetails = (UserCustomDetails) authentication.getPrincipal();
        return new ResponseMessage(ResponseStatus.SUCCESS, eventsServiceImpl.getAdminEvents(userDetails.getUserId()));
    }

    @GetMapping("/event")
    @ApiOperation(value = "获取所有事件")
    @JsonCustomFilter(type = Events.class, filter = {"eventContent"})
    public ResponseMessage getAllEvents() {
        return new ResponseMessage(ResponseStatus.SUCCESS, eventsServiceImpl.getAll());
    }

    @PostMapping("/event/{eventId}/form")
    @ApiOperation(value = "新建报名表")
    public ResponseMessage createForm(@NotNull @PathVariable int eventId, Authentication authentication) {
        UserCustomDetails userDetails = (UserCustomDetails) authentication.getPrincipal();
        // 当前活动信息
        Events thisEvent = eventsServiceImpl.getEventById(eventId);
        // 检查是否存在表单
        int hasFormId = formService.hasForm(eventId, userDetails.getUserId());
        if (hasFormId == -1) {
            // 检查活动状态,如果已经报过名但依然访问这个api则返回正在报名的表单
            if (thisEvent == null) {
                return new ResponseMessage(ResponseStatus.ERROR, "活动不存在！");
            }
            if (thisEvent.getStatus() == 3) {
                return new ResponseMessage(ResponseStatus.ERROR, "当前活动不可用！");
            }
            if (thisEvent.getEventDeadTime().before(new Date())) {
                return new ResponseMessage(ResponseStatus.ERROR, "已经超过报名截止时间！");
            }
            // 活动已经报名的表单
            List<Form> accessForm = formService.getAccessForm(eventId);
            if ((thisEvent.getEventMaxSize() - accessForm.size()) < 1) {
                return new ResponseMessage(ResponseStatus.ERROR, "活动报名人数已满！");
            }
            return new ResponseMessage(ResponseStatus.INFO, formService.createForm(eventId, userDetails.getUserId()), "表单创建成功！");
        } else {
            // 如果已经报过名但依然访问这个api则返回正在报名的表单
            return new ResponseMessage(ResponseStatus.INFO, hasFormId, "找到了一份您的表单，请不要重复提交！");
        }
    }

    @DeleteMapping("/event/{eventId}")
    @ApiOperation(value = "删除事件")
    public ResponseMessage deleteForm(@PathVariable(value = "eventId") int eid, Authentication authentication) throws Exception {
        UserCustomDetails userDetails = (UserCustomDetails) authentication.getPrincipal();
        Events thisEvent = eventsServiceImpl.getEventById(eid);
        if (thisEvent == null) {
            return new ResponseMessage(ResponseStatus.ERROR, "活动不存在！");
        }
        if (userDetails.getUserId().equals(thisEvent.getEventAdmin())) {
            return new ResponseMessage(ResponseStatus.ERROR, "你不是事件管理员,无法删除");
        }
        if (thisEvent.getStatus() == 3) {
            return new ResponseMessage(ResponseStatus.ERROR, "当前活动不可用！");
        }
        eventsServiceImpl.deleteEvent(eid);
        return new ResponseMessage(ResponseStatus.INFO, "删除成功！");
    }
}
